package com.ljs.threadpooldemo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 根据系统区别的文件上传
 */
@Slf4j
public class FileUtil {

    public static Map<String,String> upload(MultipartFile file,String path){
        Map<String,String> map=new HashMap();
        if(file.isEmpty()){
            map.put("msg","文件不能为空");
        }
        String fileName=  file.getOriginalFilename();
        String newName= UUID.randomUUID().toString()+fileName.substring(fileName.indexOf("."));
        String finalName=path+newName;
        log.info("要上传的文件{}",finalName);
        File newFile=new File(finalName);
        if(!newFile.exists()){
            try {
                newFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            map.put("msg","文件已经存在");
        }
        try {
            file.transferTo(newFile);
            map.put("msg","上传成功");
            //访问路径是/images
            map.put("newName","/images/"+newName);
        } catch (IOException e) {
            e.printStackTrace();
            map.put("msg","上传失败");
        }
       return map;
    }

    /**
     * 下载的方法
     */
    public static void  downFile(HttpServletResponse response,String fileName,File file) throws UnsupportedEncodingException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        // 设置编码
         fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        //要拿到正确的文件路径
        // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        try {

            OutputStream out = response.getOutputStream();
                InputStream in = new FileInputStream(file);
                // 循环取出流中的数据
                byte[] b = new byte[1024];
                int len;
                while ((len = in.read(b)) !=-1) {
                    out.write(b, 0, len);
                }
                in.close();
                out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
